//
//  LZAudioPlayerManager.m
//  LZMusicPlayer
//
//  Created by wulanzhou on 2016/10/14.
//  Copyright © 2016年 wulanzhou. All rights reserved.
//

#import "LZAudioPlayerManager.h"
#import <UIKit/UIKit.h>

@interface LZAudioPlayerManager (){
    UIBackgroundTaskIdentifier *_bgTaskId;
}
@property (nonatomic,strong) NSMutableDictionary *cacheAudioPlays;
@property (nonatomic,strong) NSString *currentPlayName;
@end

@implementation LZAudioPlayerManager

+ (LZAudioPlayerManager *)shareInstance
{
    static dispatch_once_t pred = 0;
    __strong static LZAudioPlayerManager *_sharedObject = nil;
    dispatch_once(&pred, ^{
        _sharedObject = [[self alloc] init]; // or some other init method
    });
    return _sharedObject;
}

- (instancetype)init{

    if (self=[super init]) {
        self.cacheAudioPlays=[[NSMutableDictionary alloc] init];
        
        //-->在通知中心注册一个事件中断的通知：
        //处理中断事件的通知
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleInterreption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
    }
    return self;
}

- (AVAudioPlayer *)playMusicWithName:(NSString *)musicName{
    
    if (musicName == nil || musicName.length == 0)  return nil;

    AVAudioPlayer *_audioPlayer=[self.cacheAudioPlays objectForKey:musicName];
    
    if (!_audioPlayer) {
        
        NSURL *url = [[NSBundle mainBundle] URLForResource:musicName withExtension:nil];
        
        if (!url)  return nil;
        
        _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
        
        if (![_audioPlayer prepareToPlay]) return nil;
        
        self.cacheAudioPlays[musicName] = _audioPlayer;            //对象是最新创建的，那么对它进行一次缓存
    }
    
    self.currentPlayName=musicName;
    
    if (![_audioPlayer isPlaying]) {                 //如果没有正在播放，那么开始播放，如果正在播放，那么不需要改变什么
        [_audioPlayer play];
    }
    return _audioPlayer;
}

- (AVAudioPlayer *)playMusicWithURL:(NSURL *)musicURL{

    if (musicURL == nil)  return nil;
    
    NSString *fname = [musicURL.path lastPathComponent];
    
    if (fname == nil || fname.length == 0)  return nil;
    
    AVAudioPlayer *_audioPlayer=[self.cacheAudioPlays objectForKey:fname];
    
    if (!_audioPlayer) {

        _audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:musicURL error:nil];
        
        if (![_audioPlayer prepareToPlay]) return nil;
        
        self.cacheAudioPlays[fname] = _audioPlayer;            //对象是最新创建的，那么对它进行一次缓存
    }
    
    self.currentPlayName=fname;
    
    if (![_audioPlayer isPlaying]) {                 //如果没有正在播放，那么开始播放，如果正在播放，那么不需要改变什么
        [_audioPlayer play];
    }
    return _audioPlayer;
    
}

- (void)pauseMusic:(NSString *)filename
{
    if (filename == nil || filename.length == 0)  return;
    
    AVAudioPlayer *player = self.cacheAudioPlays[filename];
    
    if ([player isPlaying]) {
        [player pause];
    }
}
- (void)stopMusic:(NSString *)filename
{
    if (filename == nil || filename.length == 0)  return;
    
    AVAudioPlayer *player = self.cacheAudioPlays[filename];
    
    [player stop];
    
    [self.cacheAudioPlays removeObjectForKey:filename];
    self.currentPlayName=nil;
}


#pragma mark -中断通知

//-->实现接收到中断通知时的方法
//处理中断事件
-(void)handleInterreption:(NSNotification *)sender
{
    NSLog(@"中断 class=%@,userInfo=%@",[sender.object class],sender.userInfo);
    
    if (self.currentPlayName) {
        AVAudioPlayer *_audioPlayer=[self.cacheAudioPlays objectForKey:self.currentPlayName];
        if (_audioPlayer) {
            NSLog(@"中断播放 pause");
            if ([_audioPlayer isPlaying]) {
                [_audioPlayer pause];
            }
        }else{
            NSLog(@"中断播放 停止");
            [_audioPlayer stop];
        }
    }
}

#pragma mark -后台播放功能(在applicationWillResignActive方法中实现)

- (void)setBackgroundPlayer{

    //开启后台处理多媒体事件
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    AVAudioSession *session=[AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    //后台播放
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    //这样做，可以在按home键进入后台后 ，播放一段时间，几分钟吧。但是不能持续播放网络歌曲，若需要持续播放网络歌曲，还需要申请后台任务id，具体做法是：
    _bgTaskId=[self backgroundPlayerID:_bgTaskId];
    //其中的_bgTaskId是后台任务UIBackgroundTaskIdentifier _bgTaskId;
}

//实现一下backgroundPlayerID:这个方法:
- (UIBackgroundTaskIdentifier)backgroundPlayerID:(UIBackgroundTaskIdentifier)backTaskId
{
    //设置并激活音频会话类别
    AVAudioSession *session=[AVAudioSession sharedInstance];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    [session setActive:YES error:nil];
    //允许应用程序接收远程控制
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    //设置后台任务ID
    UIBackgroundTaskIdentifier newTaskId=UIBackgroundTaskInvalid;
    newTaskId=[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
    if(newTaskId!=UIBackgroundTaskInvalid&&backTaskId!=UIBackgroundTaskInvalid)
    {
        [[UIApplication sharedApplication] endBackgroundTask:backTaskId];
    }
    return newTaskId;
}


@end
